package com.atguigu.utils;

import com.atguigu.bean.TableProcess;
import com.atguigu.common.Constant;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 只要是JDBC的任何查询操作,都可以使用
 * select count(*) from t;                    单行单列
 * select * from t where id ='xx'; id为主键    单行多列
 * select count(*) from t group by dept_id;   多行单列
 * select * from t;                           多行多列
 */
public class JdbcUtil {

    public static <T> List<T> queryList(Connection connection, String querySql, Class<T> tClass, boolean isUnderScoreToCamel) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException {

        //1.创建集合用于存放最终结果
        ArrayList<T> list = new ArrayList<>();

        //2.预编译SQL语句
        PreparedStatement preparedStatement = connection.prepareStatement(querySql);

        //3.执行查询
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        //4.解析查询结果,将每行数据转换为T对象,加入集合
        while (resultSet.next()) {
            T t = tClass.newInstance();
            for (int i = 1; i < columnCount + 1; i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                if (isUnderScoreToCamel) {
                    columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnName.toLowerCase());
                }
                //给T对象赋属性值
                BeanUtils.setProperty(t, columnName, value);
            }

            //将T对象加入集合
            list.add(t);
        }

        //5.释放资源
        resultSet.close();
        preparedStatement.close();

        //6.返回结果
        return list;
    }

    public static void main(String[] args) throws Exception {

        Connection connection = DriverManager.getConnection(Constant.MYSQL_URL, "root", "000000");
        List<TableProcess> queryList = queryList(connection,
                "select * from table_process",
                TableProcess.class,
                true);
        for (TableProcess jsonObject : queryList) {
            System.out.println(jsonObject);
        }
        connection.close();
    }
}
